/**
 * 
 */
package info.niwota.ispy;

import java.util.Calendar;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

/**
 * @author qiangli
 *
 */
public class Notifications {
	private static final int SERVICE_ID = R.string.app_name;
	
	private Notifications() {
	}
	
	public static void notify(Context ctx, String desc) {
		try {
			Notification note = new Notification(R.drawable.icon25_red, null, 0);
			PendingIntent pi = PendingIntent.getActivity(ctx, 0, new Intent(
					ctx, MainActivity.class), 0);
			note.flags |= Notification.FLAG_NO_CLEAR;
			note.flags |= Notification.FLAG_ONGOING_EVENT;
			
			if (Preferences.isWarnFlash(ctx)) {
				note.defaults |= Notification.DEFAULT_LIGHTS;
			}
			//
			boolean quiet = Preferences.isWarnQuiet(ctx);
			if (Debug.DEBUG) {
				Log.d("Notifications", "quiet: " + quiet);
			}
			if (quiet) {
				Calendar cal = Calendar.getInstance();
				int hour = cal.get(Calendar.HOUR_OF_DAY);
				quiet = (hour < 8 || hour >= 20);
				if (Debug.DEBUG) {
					Log.d("Notifications", "hour: " + hour + " quiet: " + quiet);
				}
			}
			if (!quiet && Preferences.isWarnSound(ctx)) {
				note.defaults |= Notification.DEFAULT_SOUND;
			}
			if (!quiet && Preferences.isWarnVibrate(ctx)) {
				note.defaults |= Notification.DEFAULT_VIBRATE;
			}
			//
			CharSequence title = ctx.getText(R.string.app_name);
			note.setLatestEventInfo(ctx, title, desc, pi);
			NotificationManager nm = (NotificationManager) ctx
					.getSystemService(Context.NOTIFICATION_SERVICE);
			nm.notify(SERVICE_ID, note);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void update(Context ctx) {
		add(ctx);
	}
	
	public static void add(Context ctx) {
		try {
			Notification note = new Notification(R.drawable.icon25, null, 0);
			PendingIntent pi = PendingIntent.getActivity(ctx, 0, new Intent(
					ctx, MainActivity.class), 0);
			note.flags |= Notification.FLAG_NO_CLEAR;
			note.flags |= Notification.FLAG_ONGOING_EVENT;
			//
			CharSequence title = ctx.getText(R.string.app_name);
			CharSequence desc = ctx.getText(R.string.app_tagline);
			note.setLatestEventInfo(ctx, title, desc, pi);
			NotificationManager nm = (NotificationManager) ctx
					.getSystemService(Context.NOTIFICATION_SERVICE);
			nm.notify(SERVICE_ID, note);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void remove(Context ctx) {
		try {
			NotificationManager nm = (NotificationManager) ctx
					.getSystemService(Context.NOTIFICATION_SERVICE);
			//
			nm.cancelAll();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
